package com.managermype.controller;

import java.util.Calendar;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.WebAttributes;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

import com.managermype.domain.User;
import com.managermype.util.Constant;
import com.managermype.util.Page;

/**
 * 
 * @author juandiego
 * 
 */
public class BaseController {

	@Autowired
	ServletContext servletContext = null;

	public Calendar toCalendar(String strDate) {
		String[] arrayDate = strDate.split(Constant.DATE_SEPARATOR);
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.set(toInteger(arrayDate[0]), (toInteger(arrayDate[1]) - 1), toInteger(arrayDate[2]));
			return calendar;
		}
		catch (Exception e) {
			return calendar;
		}

	}

	public Integer toInteger(String strNumber) {
		try {
			return Integer.parseInt(strNumber);
		}
		catch (Exception e) {
			return 0;
		}
	}

	public User getUserLogged() {
		try {
			return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		catch (Exception e) {
			return null;
		}
	}

	public boolean isAuthenticated() {
		if (getUserLogged() != null) {
			return Boolean.TRUE;
		} else {
			return Boolean.FALSE;
		}
	}

	public AuthenticationException getLastAuthenticationException(HttpSession session) {
		return (AuthenticationException) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	}

	public void clearLastAuthenticationException(HttpSession session) {
		session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);// Clear
																		// last
																		// Exception
	}

	@ExceptionHandler(ConversionNotSupportedException.class)
	public ModelAndView handleInternalConversionNotSupported(ConversionNotSupportedException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "Error (500) Interno en el Servidor " + ex.getMessage());
		return mav;
	}

	@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
	public ModelAndView handleMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex) {
		System.out.println("Errorfasfsadf:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "Error (406) No aceptable " + ex.getMessage());
		return mav;
	}

	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public ModelAndView handleMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "Error (415) Tipo de Medio No Soportado " + ex.getMessage());
		return mav;
	}

	@ExceptionHandler(HttpMessageNotReadableException.class)
	public ModelAndView handleMessageNotReadable(HttpMessageNotReadableException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "Petición Incorrecta (Código de Error: 400) " + ex.getMessage());
		return mav;
	}

	@ExceptionHandler(HttpMessageNotWritableException.class)
	public ModelAndView handleInternalNotWritableError(HttpMessageNotWritableException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "Error (500) Interno en el Servidor " + ex.getMessage());
		return mav;
	}

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ModelAndView handleMethodNotSupport(HttpRequestMethodNotSupportedException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "(405) Este recurso no puede ser accedido vía " + ex.getMethod());
		return mav;
	}

	@ExceptionHandler(MissingServletRequestParameterException.class)
	public @ResponseBody
	String handleExceptionMissingParameter(MissingServletRequestParameterException ex) {
		System.out.println("Error" + ex.getParameterName() + ex.getMessage());
		return "El parámetro " + ex.getParameterName() + " es obligatorio";
	}

	@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
	public ModelAndView handleNotFoundException(NoSuchRequestHandlingMethodException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "(400) Este recurso no ha sido encontrado ");
		return mav;
	}

	@ExceptionHandler(TypeMismatchException.class)
	public ModelAndView handleExceptionSintaxis(TypeMismatchException ex) {
		System.out.println("Error:" + ex.getMessage());
		ModelAndView mav = new ModelAndView();
		mav.setViewName(Page.CONTROLLER_EXCEPTION_PAGE.getJspPath());
		mav.addObject(Constant.ERROR_MESSAGE, "Petición Incorrecta (Código de Error: 400) " + ex.getMessage());
		return mav;
	}

}
